package edu.biwu.cookie04;

import edu.biwu.utils.CookieUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Cookie[] cookies = request.getCookies();
        //1.查找一个名称为lastVisited的cookie
        Cookie lastVisited = CookieUtils.getCookie(cookies, "lastVisited");
        response.setContentType("text/html;charset=UTF-8");

        if (lastVisited==null) {
            //向浏览器响应 "欢迎第一次访问"
            response.getWriter().write("欢迎第一次访问");
        } else {

            //说明首次访问,创建一个lastVisitedCookie记录当前访问时间
            //取出cookie中记录的时间,响应给浏览器
            String lastVisitedValue = lastVisited.getValue();

            //拿值解码
            //对dateStr进行解码,编码出原始值
            String decode = URLDecoder.decode(lastVisitedValue, "UTF-8");
            response.getWriter().write("上次访问时间："+decode);
        }

        //无论是第一次,第二次,第三次,....第n次访问,都需要将当前系统时间设置到cookie,响应给浏览器
        String formatTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        //给浏览器需要把空格冒号编码
        //再将日期放入cookie前,先进行编码,防止cookie不支持某些字符
        String encode = URLEncoder.encode(formatTime, "UTF-8");

        Cookie cookie = new Cookie("lastVisited", encode);
        cookie.setMaxAge(60*60*24*365);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
